package cn.b.sky.user.service.impl;

import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.utils.DatabaseUtils;
import cn.b.sky.i18n.utils.LocaleResourceBundle;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.dao.UserDao;
import cn.b.sky.user.service.OrganizationService;
import cn.b.sky.user.service.UserService;
import cn.b.sky.user.service.model.*;
import cn.b.sky.user.service.model.condition.UserCondition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @ClassName: UserServiceImpl
 * @Description:用户管理实现类
 * @author: ZhaoXin
 * @date: 2015-7-31 下午01:08:21
 * @version: V1.0
 * 
 */
@Service("userService")
public class UserServiceImpl implements UserService {
  
  private static final Logger LOG = LoggerFactory.getLogger(UserServiceImpl.class);

  @Resource
  UserDao userDao;

  @Resource
  OrganizationService organizationService;

  @Override
  public List<UserInfo> selectUserList(UserCondition userCondition) {
    if (userCondition != null) {
      return userDao.selectUserList(userCondition);
    } else {
      return null;
    }
  }

  @Override
  public int selectUserListCount(UserCondition userCondition) {
    if (userCondition != null) {
      return userDao.selectUserListCount(userCondition);
    } else {
      return 0;
    }
  }

  @Override
  public List<Language> selectAllLanaguage() {
    return userDao.selectAllLanaguage();
  }

  @Override
  public List<TimeZone> selectTimeZone() {
    return userDao.selectTimeZone();
  }

  @Override
  public void insertUser(UserInfo userInfo) {
    userDao.insertUser(userInfo);
    if (userInfo.getOrgList() != null && userInfo.getOrgList().size() > 0) {
      for (UserOrganization org : userInfo.getOrgList()) {
        userDao.insertUserOrganization(org);
      }
    }
    if (userInfo.getRoleList() != null && userInfo.getRoleList().size() > 0) {
      for (UserRole role : userInfo.getRoleList()) {
        userDao.insertUserRole(role);
      }
    }

  }

  @Override
  public List<Organization> selectOrganizationByUser(String siteCode, String userCode) {
    return userDao.selectOrganizationByUser(siteCode, userCode);
  }

  @Override
  public List<Role> selectRoleByUser(String siteCode, String userCode) {
    return userDao.selectRoleByUser(siteCode, userCode);
  }

  @Override
  public UserInfo selectUser(String siteCode, String userCode) {
    return userDao.selectUser(siteCode, userCode);
  }

  @Override
  public List<UserParameter> selectUserParameter(String siteCode, String userCode) {
    return userDao.selectUserParameter(siteCode, userCode);
  }

  @Override
  public void updateUser(UserInfo userInfo) {
    userDao.updateUser(userInfo);
    userDao.deleteUserOrganization(userInfo.getSiteCode(), userInfo.getUserCode());
    userDao.deleteUserRole(userInfo.getSiteCode(), userInfo.getUserCode());
    if (userInfo.getOrgList() != null && userInfo.getOrgList().size() > 0) {
      for (UserOrganization org : userInfo.getOrgList()) {
        userDao.insertUserOrganization(org);
      }
    }
    if (userInfo.getRoleList() != null && userInfo.getRoleList().size() > 0) {
      for (UserRole role : userInfo.getRoleList()) {
        userDao.insertUserRole(role);
      }
    }
  }

  @Override
  public BatchJobReport deleteUser(String siteCode, String userCode) {
    String cause = "";
    Boolean success = true;
    try {
      userDao.deleteUserOrganization(siteCode, userCode);
      userDao.deleteUserRole(siteCode, userCode);
      userDao.deleteUserParameter(siteCode, userCode);
      userDao.deleteUser(siteCode, userCode);
    } catch (Exception e) {
      LOG.error("{}", e);
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      if (DatabaseUtils.isConstraintsError(e.getMessage()))  {
        // 外键删除已存在提示
        cause = LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),SecurityContextUtil.getLanguageCode(),
            "dataBaseOperationPkFail.M")
            + LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),SecurityContextUtil.getLanguageCode(), "notDelete.M");
      } else {
        cause = e.getMessage();
      }
      success = false;
    }
    return new BatchJobReport(userCode, cause, success, SecurityContextUtil.getLanguageCode(),SecurityContextUtil.getSiteCode());

  }

  @Override
  public List<UserInfo> selectUserByOrganization(String siteCode, String organizationCode) {
    return userDao.selectUserByOrganization(siteCode, organizationCode);
  }

  @Override
  public List<UserInfo> selectUserNotInOrganization(String siteCode) {
    return userDao.selectUserNotInOrganization(siteCode);
  }

  @Override
  public List<UserOrganization> selectUserTree(String siteCode) {
    List<UserOrganization> userTree = new ArrayList<UserOrganization>();
    List<Organization> menuList = organizationService.selectRootOrg(siteCode, false);
    if (menuList != null) {
      for (Organization m : menuList) {
        UserOrganization uo = new UserOrganization();
        uo.setSiteCode(siteCode);
        uo.setUserCode(m.getOrganizationCode());
        uo.setUserText(m.getOrganizationText());
        uo.setNodeType("o");// 组织
        userTree.add(uo);
        getChildren(uo);
      }
    }
    // 插入不在组织中的用户分组
    UserOrganization uo = new UserOrganization();
    uo.setUserCode("notInOrg");
    uo.setUserText("未加入组织用户");
    uo.setNodeType("o");// 组织
    List<UserOrganization> children = new ArrayList<UserOrganization>();
    uo.setChildren(children);
    List<UserInfo> users = userDao.selectUserNotInOrganization(siteCode);
    if (users != null) {
      for (UserInfo u : users) {
        UserOrganization o = new UserOrganization();
        o.setUserCode(u.getUserCode());
        o.setUserText(u.getUserText());
        o.setNodeType("u");// 用户
        children.add(o);
      }
    }
    userTree.add(uo);
    return userTree;
  }

  private void getChildren(UserOrganization userOrganization) {
    // 查找用户
    List<UserOrganization> children = new ArrayList<UserOrganization>();
    userOrganization.setChildren(children);
    List<UserInfo> users = userDao.selectUserByOrganization(userOrganization.getSiteCode(),
        userOrganization.getUserCode());
    if (users != null) {
      for (UserInfo user : users) {
        UserOrganization uo = new UserOrganization();
        uo.setUserCode(user.getUserCode());
        uo.setUserText(user.getUserText());
        uo.setNodeType("u");// 用户
        children.add(uo);
      }
    }
    List<Organization> orgs = organizationService.selectOrgByParent(userOrganization.getSiteCode(),
        userOrganization.getUserCode(), false);
    if (orgs != null) {
      for (Organization m : orgs) {
        UserOrganization uo = new UserOrganization();
        uo.setSiteCode(userOrganization.getSiteCode());
        uo.setUserCode(m.getOrganizationCode());
        uo.setUserText(m.getOrganizationText());
        uo.setNodeType("o");// 组织
        children.add(uo);
        getChildren(uo);
      }
    }
  }

  @Override
  public void insertUserOrganization(List<UserOrganization> userOranizations) {
    for (UserOrganization userOranization : userOranizations) {
      userDao.insertUserOrganization(userOranization);
    }

  }

  @Override
  public void deleteUserOrganizationByOrg(String siteCode, String organizationCode) {
    userDao.deleteUserOrganizationByOrg(siteCode, organizationCode);

  }

  @Override
  public void updateUserPwd(String siteCode, String userCode, String password) {
    userDao.updateUserPwd(siteCode, userCode, password);

  }

  @Override
  public List<UserInfo> selectUserSuggests(UserCondition condition) {
    return userDao.selectUserSuggests(condition);
  }

}
